<template>
  <!-- hidden PageHeaderWrapper title demo -->
  <page-header-wrapper :title="false" >
    <a-card :body-style="{padding: '24px 32px'}" :bordered="false">
      <a-form @submit="handleAdd" :form="this.form">
        <a-form-item
          label="商品分类"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
          <a-select placeholder="请选择" v-decorator="['typeId']" @select="change">
            <a-select-option :value="i.id" v-for="i in this.option" :key="i.value">{{ i.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="商品名"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}" 
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
          <a-select v-decorator="['goodId',{ rules: [{ required: true, message: '请选择' }] }]" show-search placeholder="请选择" >
            <a-select-option :value="i.id" v-for="i in this.prodOption" :key="i.value">{{ i.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="成本"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
          <a-input
            v-decorator="[
              'commCost',{ rules: [{ required: true, message: '请输入' }] }
            ]"
            addonAfter="元"
            placeholder="请输入成本" 
            name="commCost"/>
        </a-form-item>
        <a-form-item
          label="数量"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
          <a-input
            v-decorator="[
              'size',{ rules: [{ required: true, message: '请输入' }]}
            ]"
            placeholder="请输入数量" 
            name="size"/>
        </a-form-item>
        <a-form-item
          label="往来账"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
          <a-radio-group v-decorator="['isRecord', { initialValue: 1 ,rules: [{ required: true, message: '请选择' }]}]" placeholder="请选择" >
            <a-radio :style="radioStyle" :value="1">记录供应商往来账</a-radio>
            <a-radio :style="radioStyle" :value="2">不记录供应商往来账</a-radio>
          </a-radio-group>
          
        </a-form-item>
        <a-form-item
          :wrapperCol="{ span: 24 }"
          style="text-align: center"
        >
          <a-button htmlType="submit" type="primary" icon="check">添加</a-button>
          <!-- <a-button style="margin-left: 8px">{{ $t('form.basic-form.form.save') }}</a-button> -->
        </a-form-item>
      </a-form>
    </a-card>
    <a-card :body-style="{padding: '24px 32px'}" title="入库商品清单">
      <a-table
        ref="table"
        size="default"
        rowKey="key"
        :columns="columns"
        :data-source="loadData"
      >
        <span slot="heji" slot-scope="text, record">
          <template>
            <div>{{ (record.commCost * record.size ?? 0).toFixed(2) }}</div>
          </template>
        </span>
        <span slot="isRecord" slot-scope="text, record">
          <template>
            <div v-if="record.isRecord == 1">是</div>
            <div v-else>否</div>
          </template>
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a-tag color="#D15B47" @click="handleDel(record)">删除</a-tag>
          </template>
        </span>
      </a-table>
    </a-card>
    <a-card :body-style="{padding: '24px 32px'}" :bordered="false">
      <a-form @submit="handleSubmit" :form="form1">
        <a-form-item
          label="供应商"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
          <a-select v-decorator="['supplyId',{ rules: [{ required: true, message: '请选择' }] }]" placeholder="请选择供应商" >
            <a-select-option :value="i.id" v-for="i in this.suppliesOption" :key="i.value">{{ i.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item 
          label="采购渠道" 
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
          <a-select v-decorator="['channelId']" placeholder="请选择" >
            <a-select-option :value="i.id" v-for="i in this.channelOption" :key="i.value">{{ i.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item 
          label="入库日期"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
          <a-date-picker
            v-decorator="['orderDate', { initialValue:this.toDays, rules: [{ required: true, message: '请选择' }]}]" />
        </a-form-item>
        <a-form-item
          label="备注"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
          <a-input v-decorator="['memo']" name="memo" placeholder="请输入备注"/>
        </a-form-item>
        <a-form-item
          :wrapperCol="{ span: 24 }"
          style="text-align: center"
        >
          <a-button htmlType="submit" type="primary" icon="check">提交入库</a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </page-header-wrapper>
</template>
<script>

import { getSuppliesListUsingPOST, } from '@/api/api/jingxiaoshangyunyingshangguanli.ts'
import { getGdClassListUsingPOST ,getGoodsListUsingPOST} from '@/api/api/shangpinguanli.ts'
import { getChannelListUsingPOST ,autoCodePurchaseUsingPOST} from '@/api/api/caigouguanli.ts'
import moment from 'moment'
  export default {
    name: 'InStoreDetail',
    data () {
      return {
        toDays: moment().format('YYYY-MM-DD'),
        radioStyle:{
          display: 'block',
          height: '30px',
          lineHeight: '30px',
        },
        params:{
          buyType:1,
          channelId:'',
          detailParamList:[],
          memo:'',
          orderDate:'',
          storeId:'',
          supplyId:''
        },
        queryParam: {
        pageNo:1,
        pageSize:999,
        queryCondition:'',
        status:1
      },
        option:[],
        prodOption:[],
        suppliesOption:[],
        channelOption:[],
        form: this.$form.createForm(this),
        form1: this.$form.createForm(this),
        columns: [
        {
          title: '商品名',
          dataIndex: 'goodName'
        },
        {
          title: '成本(元)',
          dataIndex: 'commCost'
        },
        {
          title: '数量',
          dataIndex: 'size'
        },
        {
          title: '合计(元)',
          dataIndex: 'heji',
          scopedSlots: { customRender: 'heji' }
        },
        {
          title: '记供应商账',
          dataIndex: 'isRecord',
          scopedSlots: { customRender: 'isRecord' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '220px',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData:[]
      }
    },
    created () {
      this.handleSearch(this.queryParam)
      this.handleProd()
      this.handleSupplies()
      this.handleChannel()
  },
    methods: {
      handleChannel(){
        getChannelListUsingPOST(this.queryParam).then((res) => {
          this.channelOption = res.data.list
        })
        .catch((error) => {
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
      },
      handleSupplies(){
        getSuppliesListUsingPOST(this.queryParam).then((res) => {
          this.suppliesOption = res.data.list
        })
        .catch((error) => {
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
      },
      removeTrim(array){
        for (let i = 0; i < array.length; i++) {
          if (array[i] == '') {
              array.splice(i, 1)
              i = i - 1
            }
          }
        return array
      },
      handleDel(record){
        const that = this
        that.$confirm({
          title: '删除',
          content: '你确定要删除这个商品吗？',
          okText: '确认',
          okType: 'danger',
          cancelText: '取消',
          onOk() {
            that.loadData.splice( that.loadData.findIndex(item => item.id === record.id), 1)
            // this.loadData = this.loadData
          },
        })
      },
      handleAdd(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.loadData.push({
            ...values,
            size:values.size,
            goodsCode: this.prodOption.find((item) => {
              return item.id == values.goodId
            })?.code,
            goodClass2: this.prodOption.find((item) => {
              return item.id == values.goodId
            })?.subId,
            goodName: this.prodOption.find((item) => {
              return item.id == values.goodId
            })?.name,
            brandName: this.prodOption.find((item) => {
              return item.id == values.goodId
            })?.brandName,
            goodId: this.prodOption.find((item) => {
              return item.id == values.goodId
            })?.id,
          })
          
        }
      })
    },
    handleSearch () {
      getGdClassListUsingPOST({...this.queryParam , classType:2}).then((res) => {
        this.option = res.data.list
      })
      .catch((error) => {
        this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
      })
    },
    handleProd(classId){
      getGoodsListUsingPOST({...this.queryParam,classId:classId}).then((res) => {
        this.prodOption = res.data.list
      })
      .catch((error) => {
        this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
      })
    },
    change(e){
      this.handleProd(e)
    },
    handleSubmit (e) {
        e.preventDefault()
        this.form1.validateFields((err, values) => {
          if (!err) {
            if(this.loadData.length == 0) {
              this.$message.error('没有可入库的商品')
              return false
            }
            const params = {
            second: values.second,
            memo: values.memo,
            orderDate: values.orderDate,
            supplyId: values.supplyId,
            storeId: this.$route.params.id,
            channelId: values.channelId,
            buyType: 1,
          }
          const data = {
            autoCodePurchaseDataList: this.loadData.map((item) => {
              return {
                brandName: item.brandName,
                commCost: item.commCost,
                goodClass2: item.subId,
                goodsName: item.goodName,
                goodsId: item.goodId,
                isRecord: item.isRecord,
                size:Number(item.size),
              }
            }),
          }
            autoCodePurchaseUsingPOST({  ...params}, [...data.autoCodePurchaseDataList]).then((res) => {
              this.$message.success('操作成功')
              this.$router.push({ path: `/purchasing/inStoreRecord/detail/${res.data.id}` })
              this.form.resetFields()
              this.form1.resetFields()
            }).catch((error) => {
              this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
          }
        })
      }
    },
    
  }
</script>